<template>
  <el-dialog
    class="deliver-dialog"
    :width="dialogWidth"
    append-to-body
    top="5vh"
    title="发送物流"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="handClose"
  >
    <div class="deliver-container">
      <div class="deliver-table" v-if="orderDataNumList.length > 0">
        <div class="head-content">
            <span>已选中订单</span>
            <div class="image-content" @click="onClickMore">
                <i class="el-icon-arrow-up" v-if="isMore"></i>
                <i class="el-icon-arrow-down" v-else></i>
            </div>
        </div>

      <el-table :data="orderDataNumList" stripe border>
        <el-table-column label="订单编号" prop="orderNo"></el-table-column>
        <el-table-column label="用户名" prop="patientName"></el-table-column>
        <el-table-column label="医生姓名" prop="docName"></el-table-column>
        <el-table-column label="订单时间" prop="orderTime"></el-table-column>
        <el-table-column label="处方类型" prop="prescriptionType">
          <template slot-scope="scope">
            <span v-if="scope.row.infos[0].prescriptionType == 1">饮片</span>
            <span v-if="scope.row.infos[0].prescriptionType  == 2" type="success">成药处方</span>
            <span v-if="scope.row.infos[0].prescriptionType == 3" type="danger">颗粒剂</span>
            <span v-if="scope.row.infos[0].prescriptionType == 4" type="danger">输液处方</span>
            <span v-if="scope.row.infos[0].prescriptionType == 5" type="danger">敷贴处方</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" prop="payStatus">
            <template slot-scope="scope">
        <template v-if="scope.row.payStatus == 0">
          <el-tag>未支付</el-tag>
        </template>
        <template v-if="scope.row.payStatus == 1">
          <el-tag type="success">已支付</el-tag>
        </template>
        <template v-if="scope.row.payStatus == 3">
          <el-tag type="danger">已部分退款</el-tag>
        </template>
        <!-- <template v-if="scope.row.payStatus == 3">
          <el-tag type="danger">已全部退款</el-tag>
        </template> -->
      </template>
        </el-table-column>
        <el-table-column label="支付金额" prop="totalFee"></el-table-column>
        <el-table-column label="支付时间" prop="payTime"></el-table-column>
        <el-table-column label="提货类型">邮寄</el-table-column>
        
      </el-table>
      </div>
      <div class="deliver-offline">
        <el-radio-group v-model="postData.offline" @change="onChangeOffline">
          <el-radio-button :label="0">线上发货</el-radio-button>
          <el-radio-button :label="1">线下发货</el-radio-button>
        </el-radio-group>
      </div>
      <el-form 
        class="deliver-form" 
        label-width="120px"
        :model="postData"
        :rules="rules"
        ref="form"
      >
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="订单编号：">{{ orderNof }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件人：">{{ postData.srcName }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="寄件人电话：">{{ postData.srcPhone }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件人省市区：">{{ postData.srcProvince }}/{{ postData.srcCity }}/{{ postData.srcDistrict }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="寄件地址：">{{ postData.srcAddress }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人：" prop="destName">
              <el-input v-model="postData.destName" :disabled="showDetail" placeholder="请输入收件人" />
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="收件电话：" prop="destPhone">
              <el-input v-model="postData.destPhone" :disabled="showDetail" placeholder="请输入收件电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人省市区：" prop="destProvince">
              <el-cascader
                ref="cascader"
                v-if="cascaderVisible"
                placeholder="收件人省市区"
                v-model="cascaderValue"
                @change="handleChange"
                style="width: 100%"
                :options="options"
                :props="regionProps"
              >
              </el-cascader>
              <template v-if="showDetail">{{ postData.destProvince }}/{{ postData.destCity }}/{{ postData.destDistrict }}</template>
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="收件地址：" prop="destAddress">
              <el-input v-model="postData.destAddress" :disabled="showDetail" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄托物名称：" prop="consignment">
              <el-input v-model="postData.consignment" :disabled="showDetail" placeholder="请输入寄托物名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="postData.offline === 0">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="顺丰产品类型：" prop="expressType">
                <el-select v-model="postData.expressType" :disabled="showDetail" placeholder="请选择顺丰产品类型">
                  <el-option label="陆运" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参评编号：" prop="productCode">
                <el-select v-model="postData.productCode" :disabled="showDetail" placeholder="请选择">
                  <el-option label="中药寄递" value="CHINESE_HERBAL"></el-option>
                  <el-option label="病案寄递" value="MEDICAL_CHART"></el-option>
                  <el-option label="其他" value="OTHER"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
          </el-row>
          <el-row :gutter="20">
              <el-col :span="12">
              <el-form-item label="付款方式：" prop="payMethod">
                <el-select v-model="postData.payMethod" :disabled="showDetail" placeholder="请选择付款方式">
                  <el-option label="寄付月结" :value="1"></el-option>
                  <el-option label="到付" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保价金额：" prop="statementValue">
                <el-input-number v-model="postData.statementValue" :disabled="showDetail" placeholder="0" :min="0" />
              </el-form-item>
            </el-col>
            
          </el-row>
          <el-row :gutter="20">
              <el-col :span="12">
              <el-form-item label="重量：" prop="parcelWeighs">
                <el-input-number v-model="postData.parcelWeighs" :disabled="showDetail" placeholder="0" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="包裹数量：" prop="packagesNo">
                <el-input-number v-model="postData.packagesNo" :disabled="showDetail" placeholder="1" :min="1" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="下次发货时间：" prop="nextDeliveryDate">
                <el-date-picker
                  v-model="postData.nextDeliveryDate"
                  value-format="yyyy-MM-dd"
                  :disabled="showDetail"
                  :clearable="false"
                  :editable="false"
                  :picker-options="pickerOptions"
                  type="date"
                >
                </el-date-picker>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="备注：" prop="remark">
                <el-input v-model="postData.remark" :disabled="showDetail" type="textarea" :rows="4" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="快递公司：" prop="expressChannel">
                <el-select
                  v-model="postData.expressChannel"
                  placeholder="请选择快递公司"
                  @change="onExpressChannel"
                  :disabled="showDetail"
                  
                >
                  <template v-for="item in expressChannel">
                    <el-option
                      :label="`${item.text}(${item.prefix})`"
                      :value="item.id"
                      :key="item.id"
                    />
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快递单号：" prop="mailNo">
                <el-input
                  v-model="postData.mailNo"
                  :disabled="showDetail"
                  @change="onMailNo"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template v-if="showDetail">
        <el-button @click="onBack">返回</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">提交</el-button>
        <el-button @click="onClose">关闭</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import { addOrder, queryDestInfo, queryOrder, queryLazyTree, cancelThirdOrder } from "@/api/charges/logistics";
import { mapGetters } from "vuex";

export default {
  name: "goUnifyDeliver",
  data() {
    return {
      visible: false,
      data: [],
      orderDataList:[],
      orderDataNumList:[],
      orderNos:'',
      orderNof: null,
      isMore:false,
      postData: {
        consignment: "ZY",
        destAddress: null,
        destCity: null,
        destDistrict: null,
        destName: null,
        destPhone: null,
        destProvince: null,
        expressType: 2,
        orderNo: null,
        packagesNo: 1,
        parcelWeighs: null,
        payMethod: 1,
        productCode: "CHINESE_HERBAL",
        remark: null,
        srcAddress: null,
        srcCity: null,
        srcDistrict: null,
        srcName: null,
        srcPhone: null,
        srcProvince: null,
        statementValue: 0,
        nextDeliveryDate: null,
        offline: 0,
        expressChannel: 0,
        expressName: null,
        mailNo: null,
      },
      rules: {
        destName: [
          { required: true, message: "请输入收件人名称", trigger: "blur" },
        ],
        destAddress: [
          { required: true, message: "请输入收件详细地址", trigger: "blur" },
        ],
        destPhone: [
          { required: true, message: "请输入收件人电话", trigger: "blur" },
        ],
        consignment: [
          { required: true, message: "请输入寄托物名称", trigger: "blur" },
        ],
        expressType: [
          { required: true, message: "请选择产品类型", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "请选择参评编号", trigger: "blur" },
        ],
        payMethod: [
          { required: true, message: "请选择付款方式", trigger: "blur" },
        ],
        statementValue: [
          { required: true, message: "请输入保价", trigger: "blur" },
        ],
        parcelWeighs: [
          { required: true, message: "请输入物品重量", trigger: "blur" },
        ],
        destProvince: [
          { required: true, message: "请选择收件人省市区", trigger: "blur" },
        ],
        expressChannel: [
          { required: true, message: "请选择快递公司", trigger: ["blur","change"] },
        ],
        mailNo: [
          { required: true, message: "请输入快递单号", trigger: ["blur","change"] },
          { 
            trigger: ["blur","change"],
            validator(rule, value, callback) {
              if(!value || value.length < 3) {
                callback(new Error("请输入正确的单号"));
              }
              callback();
            }
          },
        ],
      },
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let parent = node.value || "00";
          queryLazyTree(node.value || "00").then(res => {
            let data = [];
            let level = node.level;
            res.forEach(item => {
              data.push({
                value: item.value,
                label: item.title,
                leaf: level >= 2
              });
            });
            resolve(data);
          });
        }
      },
      pickerOptions: {
        disabledDate(d) {
          let time = new Date();
          return d.getTime() < time.getTime();
        }
      },
      options: [],
      cascaderValue: [],
      submitLoading: false,
      cascaderVisible: true,
      oldData: null,
      showDetail: false,
      selectExpress: null,
    }
  },
  created() {
    this._initView();
  },
  computed: {
    ...mapGetters(["expressChannel"]),
    dialogWidth() {
      return window.innerWidth * 0.9 + "px";
    }
  },
  methods: {
    open(orderNo,orderNos,orderList) {
      this.orderDataList = orderList;
      this.orderNos = orderNos;
      this.orderNof = orderNo;
      this.postData.orderNo = orderNo;
      this.postData.offline = 0;
      this.postData.mailNo = null;
      this.postData.expressChannel = 0;
      this.postData.expressName = "顺丰";
      if(this.orderDataList.length > 0) {
          this.orderDataNumList = [];
          this.orderDataNumList.push(this.orderDataList[0]);
      }
      this._queryDestInfo();
      this.onExpressChannel(1);

      this.visible = true;
    },
    onClose(){
      this.visible=false;
    //   this.$parent.crud.refresh();
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if(valid) {
          this.submitLoading = true;
          this.postData.orderNo = this.orderNos;
          let data = {
            ...this.postData,
          }
          if(data.expressChannel > 1) {
            data.expressChannel = 1;
          }
          addOrder(data).then(() => {
            this.visible=false;
            this.$parent.crud.refresh();
            this.$parent.resetUnifyData();
            this._success();
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    onClickMore(){
        this.isMore = !this.isMore;
        this.orderDataNumList = [];
        if(this.isMore){
            this.orderDataNumList = this.orderDataList;
        }else{
        if(this.orderDataList.length > 0){
          this.orderDataNumList.push(this.orderDataList[0]);
         }
        }
    },
    getDetail(row) {
      this.oldData = {
        postData: this.postData,
        cascaderValue: this.cascaderValue
      }
      this.postData = row;
      this.cascaderVisible = false;
      this.showDetail = true;
    },
    handleChange() {
      let nodes = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
      this.postData.destProvince = nodes[0];
      this.postData.destCity = nodes[1];
      this.postData.destDistrict = nodes[2];

      this.postData.provinceCode = this.cascaderValue[0];
      this.postData.cityCode = this.cascaderValue[1];
      this.postData.areaCode = this.cascaderValue[2];
    },
    onBack() {
      this.postData = this.oldData.postData;
      this.showDetail = false;
      this.oldData = null;
      this.cascaderVisible = true;
      this.$nextTick(() => {
        this._setCascaderValue();
      });
    },
    handClose() {
      if(this.showDetail) {
        this.showDetail = false;
        this.oldData = null;
      }
      this._resetForm();
    },
    cancelOrder({ bspOrderNo }) {
      this.submitLoading = true;
      cancelThirdOrder(bspOrderNo).then(() => {
        this._success();
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    onChangeOffline() {
      if(this.postData.offline === 0) {
        // 线上发货，单号非必填
        this.rules.mailNo[0].required = false;
        this.postData.mailNo = null;
        this.postData.expressChannel = 0;
        this.postData.expressName = "顺丰";
      } else {
        // 线下发货，单号必填
        this.postData.expressChannel = 0;
        this.onExpressChannel(0);
        this.rules.mailNo[0].required = true;
      }
    },
    onExpressChannel(value) {
      for(let item of this.expressChannel) {
        if(item.id === value) {
          this.selectExpress = item;
          this.postData.expressName = item.text;
          this.postData.mailNo = item.prefix;
          break;
        }
      }
    },
    onMailNo(value) {
      if(!value) return;
      value = value.trim();
      let prefix = this.selectExpress.prefix;
      if(value.indexOf(prefix) != 0) {
        this.postData.mailNo = prefix + value;
      } else {
        this.postData.mailNo = value;
      }
    },
    _initView() {
      this._loadLazyTree({
        children: this.options,
        parent: "00"
      });
    },
    _queryDestInfo() {
      queryDestInfo(this.postData.orderNo).then(res => {
        this.postData.srcName = res.store.storeName;
        this.postData.srcAddress = res.store.address;
        this.postData.srcCity = res.store.city;
        this.postData.srcProvince = res.store.province;
        this.postData.srcDistrict = res.store.area;
        this.postData.srcPhone = res.store.phone;
        if(res.order) {
          this.postData.destPhone = res.order.phone;
          this.postData.destAddress = res.order.address;
          this.postData.destCity = res.order.city;
          this.postData.destDistrict = res.order.area;
          this.postData.destName = res.order.username;
          this.postData.destProvince = res.order.province;
          this.postData.provinceCode = res.order.provinceCode,
          this.postData.cityCode = res.order.cityCode,
          this.postData.areaCode = res.order.areaCode

          this._setCascaderValue();
        }
      });
    },
    _queryOrder() {
      let length = this.data.length;
      if(length > 0) this.data.splice(0, length - 1);
      queryOrder(this.postData.orderNo).then(res => {
        this.data = res;
      });
    },
    _success() {
      this.$notify({
        title: "操作成功",
        type: "success"
      });
      this.submitLoading = false;
    //   this._queryOrder();
      // this._resetForm();
    },
    _resetForm() {
      this.$refs.form.resetFields();
      this.cascaderVisible = [];
      this.cascaderVisible = false;
      this.$nextTick(() => {
        this.cascaderVisible = true;
      });
    },
    _loadLazyTree({ parent, children}) {
      queryLazyTree(parent).then(res => {
        res.forEach(item => {
          children.push({
            value: item.value,
            label: item.title
          });
        });
      });
    },
    _setCascaderValue() {
      let { provinceCode,cityCode,areaCode } = this.postData;
      this.cascaderValue = [ provinceCode, cityCode, areaCode ];
      let cascader = this.$refs["cascader"];  
      cascader.panel.activePath=[]; 
      cascader.panel.loadCount=0;
      cascader.panel.lazyLoad();
    }
  }
}
</script>

<style>
.deliver-table {
  margin-bottom: 10px;
}
.deliver-offline {
  margin-bottom: 10px;
}
.head-content {
   color:#333;
   font-weight:500;
   padding-bottom:12px;
   display: flex;
   flex-direction: row;
   justify-content: space-between;
}
.image-content {
  width: 30px;
  display: flex;
  flex-direction: row;
  justify-content: end;
}
</style>